<?php

//error_reporting(0);

require dirname(__DIR__) . '/F.php';

use FiradioPHP\F;

$oRes = new \FiradioPHP\Routing\Response();
$oRes->fBeginTime = microtime(TRUE);
//$oRes->setParam('IPADDR', filter_input(INPUT_SERVER, 'HTTP_X_REAL_IP'));
$oRes->setParam('IPADDR', filter_input(INPUT_SERVER, 'HTTP_X_FORWARDED_FOR'));
$oRes->path = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : ''; //3：输入用户请求路径
$sRawContent = (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') ? file_get_contents('php://input') : NULL;
$oRes->aRequest = getParam($sRawContent); //4：用户请求数据
$oRes->setParam('sRawContent', $sRawContent);

$oRes->assign('ret', 0);
try {
    F::$aInstances['router']->execAction($oRes);
} catch (\Exception $ex) {
    $sCode = $iCode = $ex->getCode();
    if (!empty($ex->sCode)) {
        $sCode = $ex->sCode;
    }
    $sMsg = $ex->getMessage();
    if ($sCode === 'end') {
        exit($sMsg);
    }
    if ($sCode === 'ActionNotFound') {
        $sMsg = '错误：【service参数值】已改变，请到API调试页获取新的service参数值';
    }
    $oRes->assign('ret', $iCode);
    $oRes->assign('code', (string) $sCode);
    $oRes->assign('msg', $sMsg);
}

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($oRes->aResponse);

function getParam($sRawContent) {
    if (substr($sRawContent, 0, 1) === '{') {
        return json_decode($sRawContent, true);
    }
    return array();
}
